<?php
/**
 * 抢购的EDM内容生产器
 */
class EDM_Qiang extends EDM
{
	private $_split;
	private $_screenshot;
	private $_path_local, $_path_CDN;

	public function __construct ()
	{
		$this->_screenshot = Kohana::config('qiang.edm.screenshot');
		$this->_split      = Kohana::config('qiang.edm.cols');
		$this->_path_local = Kohana::config('qiang.edm.images.local_path');
		$this->_path_CDN   = Kohana::config('qiang.edm.images.cdn_path');
		$this->_path_zip   = Kohana::config('qiang.edm.images.cdn_archive');

		try {

			// cleanup dir
			utility::delete_all_dir($this->_path_local);
			mkdir($this->_path_local, 0777);

			$today = date("Ymd");
			$this->_path_local = $this->_path_local.'/'.$today;
			$this->_path_CDN   = $this->_path_CDN.'/'.$today;
			mkdir($this->_path_local, 0777);
		}
		catch (Exception $e)
		{
		}
	}

	protected function edm_tpl ()
	{
		return Kohana::config('qiang.edm.tpl');
	}

	protected function edm_data ()
	{
		$links = $this->links();
		$images= $this->crop();

		$items = array();
		$i     = 0;
		foreach ($links as $link)
		{
			$img = $images[$i++];
			$items[] = array('link' => $link, 'image' => $img);
		}

		return $items;
	}

	/**
	 * 回调函数：自动打包edm上传的图片
	 *
	 * @return	void
	 */
	protected function save_successfully ()
	{
		$edm_dir = $this->_path_zip;
		system("cd $edm_dir && zip -r qiang.zip edm");
	}

	private function links () 
	{
		$url  = 'http://jia.focus.cn/qiang';
		$content = file_get_contents ($url);
		if (preg_match_all('(http:\/\/jia\.focus\.cn/shop/goods/\d+)', $content, $m))
		{
			$links = array_unique($m[0]);
		}

		return $links;
	}

	/**
	 * 切割图片(截图)
	 */
	private function crop ()
	{
		$xBase = 195;
		$yBase = 296;
		$w     = 344;
		$h     = 424;
		$total = 12;
		$split = $this->_split;
		$images = array();

		$src = imagecreatefrompng($this->_screenshot);
		
		for ($i = 0; $i < $total; ++$i)
		{
			$xPadding = $i % $split * $w;
			$yPadding = floor($i / $split) * $h;
		
			$x   = $xBase + $xPadding;
			$y   = $yBase + $yPadding;
			$fnLocal  = $this->_path_local."/$i.jpg";
			$fnRemote = $this->_path_CDN."/$i.jpg";
			$images[] = $fnRemote;
			$img = imagecreatetruecolor($w, $h);
			if (imagecopy($img, $src, 0, 0, $x, $y, $w, $h))
			{
				imagejpeg($img, $fnLocal, 90);
			}
			imagedestroy($img);
		}

		imagedestroy($src);
		return $images;

	} // crop
}
